# coding=utf8
import commands
import ConfigParser
import os
import datetime

DATETIME_FORMAT = '%Y-%m-%d-%H-%M-%S'
DEFAULT_CHARSET = "utf8"
DEFAULT_FILE_PATH = "/tmp/mysqldump"
DEFAULT_DATABASE = "mysql"
DAY_OF_WEEKS = 7
NO_PERMISSION = 13


def load_config(conf, sections):
    cfg_dict = {"user": conf.get(sections, "user"), "password": conf.get(sections, "password"),
                "host": conf.get(sections, "host"), "port": conf.get(sections, "port"),
                "database": conf.get(sections, "database")
                }
    if not cfg_dict["database"]:
        cfg_dict["database"] = DEFAULT_DATABASE
    cfg_dict["charset"] = conf.get(sections, "charset")
    if not cfg_dict["charset"]:
        cfg_dict["charset"] = DEFAULT_CHARSET
    cfg_dict["file_path"] = conf.get(sections, "file_path")
    if not cfg_dict["file_path"]:
        cfg_dict["file_path"] = DEFAULT_FILE_PATH
    return cfg_dict


def remove_backup_week_ago(config):
    back_path = os.path.join(config["file_path"], config["database"])
    try:
        os.makedirs(back_path)
    except OSError, e:
        if e.errno == NO_PERMISSION:
            print(e.message)
            return
    files = os.listdir(back_path)
    now_datetime = datetime.datetime.now() - datetime.timedelta(days=DAY_OF_WEEKS)
    for f in files:
        try:
            f_datetime = datetime.datetime.strptime(f, DATETIME_FORMAT)
            if f_datetime < now_datetime:
                os.remove(os.path.join(back_path, f))
        except ValueError, e:
            print(e.message)
        except OSError, e:
            print(e.message)


def backup_now(config):
    back_path = os.path.join(config["file_path"], config["database"])
    try:
        os.makedirs(back_path)
    except OSError, e:
        if e.errno == NO_PERMISSION:
            print(e.message)
            return
    current_datetime = datetime.datetime.now()
    str_now = current_datetime.strftime(DATETIME_FORMAT)
    str_cmd = 'mysqldump --host={0} --port={1} --user={2} --password={3} --databases {4} --default-character-set={5} > {6}'.format(
        config["host"],
        config["port"],
        config["user"],
        config["password"],
        config["database"],
        config["charset"],
        back_path + "/" + str_now
    )
    print(str_cmd)
    status, output = commands.getstatusoutput(str_cmd)
    print(output)


def main():
    all_conf = ConfigParser.ConfigParser()
    all_conf.read('backup_mysql.cfg')
    sections = all_conf.sections()
    for s in sections:
        config = load_config(all_conf, s)
        remove_backup_week_ago(config)
        backup_now(config)
        print("back {0} over".format(s))


if __name__ == '__main__':
    main()

